from fastapi import APIRouter, UploadFile, File, HTTPException, Query, Request, Depends
from typing import List
from app.services.upload_service import UploadService
from app.utils.response_util import success_response, error_response
from app.utils.jwt_utils import verify_token

router = APIRouter(prefix="/api/upload", tags=["文件上传"])

# 创建上传服务实例
upload_service = UploadService()

@router.post("/image")
async def upload_single_image(
    file: UploadFile = File(...),
    request: Request = None
):
    """上传单个图片 - 无需认证"""
    try:
        result = await upload_service.upload_single_image(file, request)
        return success_response(data=result, message="图片上传成功")
    except Exception as e:
        return error_response(message=str(e))

@router.post("/images")
async def upload_multiple_images(
    files: List[UploadFile] = File(...),
    request: Request = None
):
    """上传多个图片 - 无需认证"""
    try:
        if len(files) > 10:  # 限制最多上传10张图片
            return error_response(message="一次最多只能上传10张图片")
        
        result = await upload_service.upload_multiple_images(files, request)
        return success_response(data=result, message="批量上传完成")
    except Exception as e:
        return error_response(message=str(e))

@router.get("/image/info")
async def get_image_info(
    file_url: str = Query(..., description="图片URL")
):
    """获取图片信息 - 无需认证"""
    try:
        import os
        if file_url.startswith('/static/'):
            file_path = file_url.replace('/static/', 'static/')
        else:
            file_path = file_url
        
        if not os.path.exists(file_path):
            return error_response(message="图片不存在")
        
        file_stat = os.stat(file_path)
        return success_response(data={
            "file_url": file_url,
            "file_size": file_stat.st_size,
            "created_time": file_stat.st_ctime,
            "modified_time": file_stat.st_mtime
        })
    except Exception as e:
        return error_response(message=str(e))

@router.delete("/image")
async def delete_image(
    file_url: str = Query(..., description="图片URL"),
    token: str = Depends(verify_token)
):
    """删除图片 - 需要认证"""
    try:
        success = await upload_service.delete_image(file_url)
        if success:
            return success_response(message="图片删除成功")
        else:
            return error_response(message="图片删除失败")
    except Exception as e:
        return error_response(message=str(e)) 